package com.mindata.blockchain.core.controller;

import com.mindata.blockchain.block.PairKey;
import com.mindata.blockchain.common.exception.TrustSDKException;
import com.mindata.blockchain.core.bean.BaseData;
import com.mindata.blockchain.core.bean.ResultGenerator;
import com.mindata.blockchain.core.manager.DbBlockManager;
import com.mindata.blockchain.core.service.PairKeyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author wuweifeng wrote on 2018/3/7.
 */
@RestController
@RequestMapping("/pairKey")
@Api(description = "账户操作")
public class PairKeyController {
    @Resource
    private PairKeyService pairKeyService;
    @Resource
    private DbBlockManager dbBlockManager;

    /**
     * 生成公钥私钥
     */
    @PostMapping("/random")
    @ApiOperation(value = "生成公钥私钥")
    public BaseData generate() throws TrustSDKException {
        PairKey pairKey = pairKeyService.generate();

        //如果没有发现挖矿账号, 则优先创建挖矿账号
        String coinBasePubKey = dbBlockManager.getCoinBasePubKey();
        if (StringUtils.isBlank(coinBasePubKey)) {
            dbBlockManager.putCoinBasePubKey(pairKey.getPublicKey());
        }
        return ResultGenerator.genSuccessResult(pairKey);
    }
}
